package com.biwin.core.main.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * BiWin Framework Started Event
 *
 * @author biwin
 * @since 0.0.1
 */
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class BwStartedListener implements ApplicationListener<ApplicationStartedEvent> {
    private static final Logger log = LoggerFactory.getLogger(BwStartedListener.class);

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        printInfo(event.getApplicationContext());
    }

    private void printInfo(ApplicationContext applicationContext) {
        Environment env = applicationContext.getEnvironment();
        String host = "127.0.0.1";
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String port = env.getProperty("server.port");
        log.info(AnsiOutput.toString(AnsiColor.RED, "Application '{}' is running! Access URLs:"), env.getProperty("spring.application.name"));
        log.info(AnsiOutput.toString(AnsiColor.GREEN, "Local:       http://localhost:{}/"), env.getProperty("server.port"));
        log.info(AnsiOutput.toString(AnsiColor.GREEN, "External:    http://{}:{}/"), host, port);
        log.info(AnsiOutput.toString(AnsiColor.GREEN, "Swagger Doc: http://{}:{}/doc.html"), host, port);
    }
}
